/**
 * 
 */
package hu.cubussapiens.cms;

import hu.cubussapiens.facts.StringData;
import hu.cubussapiens.facts.query.Query;
import hu.cubussapiens.facts.query.QueryContext;
import hu.cubussapiens.facts.query.xml.QueryParser;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author balage
 *
 */
public class RootServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1534353453655646534L;

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user != null) {
        	resp.setContentType("text/plain");
            resp.getWriter().println("Hello, " + user.getNickname());
        } else {
            //resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        	resp.setContentType("text/plain");
            resp.getWriter().println("Please log in to continue..");
        }
	}
	
	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		try {
			List<Query> queries = QueryParser.parse(req.getInputStream());
			resp.setContentType("text/plain");
			QueryContext qc = new QueryContext(resp.getWriter());

			for(Query q : queries){
				for(Long l : q.execute(qc)){
					StringData data = qc.getData(l);
					//resp.getWriter().println("result: "+l);
					if (data != null){
						//resp.getWriter().println("Access control check: "+data.getRead());
						if (qc.canAccess(data.getRead()))
							resp.getWriter().println(URLEncoder.encode(data.getData(),"UTF-8"));
						else{
							//resp.getWriter().println("Access denied: "+data.getRead());
						}
					}else{
						//resp.getWriter().println("Can't find!");
					}
				}
			}
		} catch (ParserConfigurationException e) {
			throw new ServletException(e);
		} catch (SAXException e) {
			throw new ServletException(e);
		}
	}
	
}
